package com.jzoffer2;


import ds.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No32_3
 * @description
 * @date 2021/1/30 下午5:37
 */
public class No32_3 {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(9);
        TreeNode t3 = new TreeNode(20);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);
        t1.left = t2;
        t1.right = t3;
        t3.left = t4;
        t3.right = t5;
        List<List<Integer>> res = levelOrder(t1);
        for (int i = 0; i < res.size(); i++) {
            List<Integer> ret = res.get(i);
            for (int j = 0; j < ret.size(); j++) {
                System.out.print(ret.get(j));
                System.out.print(" ");
            }
            System.out.println();
        }
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int floor = 1;
        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> ret = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode t = queue.poll();
                if((floor & 1) == 1){
                    ret.add(t.val);
                }else{
                    ret.add(0,t.val);
                }
                if(t.left != null){
                    queue.offer(t.left);
                }
                if(t.right != null){
                    queue.offer(t.right);
                }
            }
            floor++;
            res.add(ret);
        }
        return res;

    }


}
